package controllers.admin;

import services.admin.MenuService;
import controllers.admin.permission.AuthorityController;
import controllers.deadbolt.RestrictedResource;
import models.permission.User;
import models.permission.Menu;
import play.libs.Crypto;
import play.modules.router.Get;
import play.modules.router.Post;
import utils.JSON;
import utils.R;

import java.util.List;

/**
 * Created by FireFire on 3/24 0024.
 * Admin index
 */
@RestrictedResource(name="/tts/admin/index")
public class Admin extends AuthorityController {

    @Get("/tts/admin/index")
    public static void index() {
        render();
    }

    /**
     * 当前用户信息
     */
    @Get("/tts/admin/currentUser")
    public static void currentUserForMenu(){
        User user = getCurrentUser();
        R r = R.ok().putUser(user);
        String json = JSON.excludeWithoutExpose().toJson(r);
        renderJSON(json);
    }

    private static User getCurrentUser(){
        return currentUser();
    }
    /**
     * 当前用户的菜单列表
     */
    @Get("/tts/admin/currentUserMenu")
    public static void currentUserMenu(){
        User user = getCurrentUser();
        List<Menu> menuList = MenuService.menuList(user);
        R r = R.ok().put("menuList",menuList);
        String json = JSON.excludeWithoutExpose().toJson(r);
        renderJSON(json);
    }

    @Post("/tts/sys/user/password")
    public static void changePassword(String password, String newPassword){
        User user = getCurrentUser();
        String encryptAES = Crypto.encryptAES(password);
        if(user.encryptedPassword.equals(encryptAES)){
            user.setPassword(newPassword);
            user.save();
            R r = R.ok();
            renderJSON(r);
        }else {
            R r = R.error("原密码不正确");
            renderJSON(r);
        }
    }
}
